(function ($) {


    let formType={

        Questionnaire:1,
        Paper:2


    },designType={

        Preview:"preview",
        Design:"design",

    }

    let formDesign = function () {
        let self = this;
        self.textdropdownClick = true;
        self.mouseX = 0; //鼠标的位置
        self.mouseY = 0; //鼠标的位置
        self.controlHtml = ""; //被选中的控件
        self.isCanBePlaced = false; //是否可以放置
        self.isDownControl = false; //是否按下了控件
        self.formLeft = 0;//form表单的坐标
        self.isMobile=function (){
            return /Android|iPhone|iPad|iPod|BlackBerry|webOS|Windows Phone|SymbianOS|IEMobile|Opera Mini/i.test(navigator.userAgent);
        }
        self.type=designType.Design
        self.formTop = 0;
        self.formRight = 0;
        self.formBottom = 0;
        self.object = null; //中部控件
        self.objectIndex = 0; //中部控件正在操作的id
        self.requiredNotify="此项为必填项，请填写！"
        self.formatNotify="格式不正确,请调整";
        self.regexMap={
            "noCheck":{"name":"不检验","exp":"","msg":""},
            "num":{"name":"数字","exp":"^[0-9]+$","msg":"只能是数字"},
            "chinese":{"name":"汉字","exp":"^[\u4e00-\u9fa5]{0,}$'","msg":"只能是汉字"},
            "mail":{"name":"邮箱","exp":"^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$","msg":"只能是邮箱"},
            "phone":{"name":"手机号","exp":"^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$","msg":"只能是手机号"},
            "idCard":{"name":"身份证","exp":"^((d{18})|([0-9x]{18})|([0-9X]{18}))$","msg":"只能是身份证"},
            //"custom":{"name":"自定义","exp":"","msg":""},
        };
        self.regOptions=function (){
            let options=[];
            for (let exp in self.regexMap){
                options.push({"key":exp,"value":self.regexMap[exp]});
            }
            return options;
        }
        self.defaultBtns = {
            //默认按钮  移动和删除
            move: {class: 'mdi mdi-cursor-move control-move'},
            delete: {class: 'mdi mdi-delete-forever control-delete'},
            up: {class: 'mdi mdi-arrow-up control-up'},
            down: {class: 'mdi mdi-arrow-down control-down'},
        };
        self.controlCache = [];
        self.getUUID=function(tag){
            return  tag + '_' + (performance.timing.navigationStart+performance.now()).toString().replaceAll('.','')
        };
        self.controlMap = {
            //控件英文名
            text:function (){

                let json={
                    name: '文本框', //控件名称
                    icon: 'mdi mdi-clipboard-outline', //控件图标
                    datas: {
                        //控件属性
                        //对象名:{name:"属性名称",value:"默认值",type:"text(文本类型)|number(数字类型)|date(日期型)|select(下拉选择)|radio(单选框)",options(仅支持下拉和单选框):{ 选项1: "值1", 选项2: "值1",选项3:"other(如果值为other,下拉选择支持自定义输入)" }}
                        name: {name: '控件名称', value: '文本框', type: 'text'},
                        placeholder: {name: '提示语句', value: '', type: 'text'},
                        // value: {name: '默认内容', value: '', type: 'text'},
                        check: {
                            name: '快捷校验规则',
                            value:"", //支持默认验证多选(多个用逗号分隔)
                            options:self.regOptions(),
                            type: 'select'
                        },

                        required: {name: '是否必填', value: 0, options:[{"label":"选填","value":0},{"label":"必填","value":1}], type: 'radio'},
                        id: {name: '主键id', value: 0, type: 'hidden'},
                        uuid:{name: '控件标识', value:"", type: 'hidden'},
                        ans:{name: '正确答案', value: '', type: 'hidden',placeholder:"正确答案"},
                    },
                    getHtml: function () {
                        return '<input name="' + this.datas.uuid.value + '" type="text" class="form-control form-val">'
                    },
                };
                if(self.fType===formType.Paper){
                    json.datas.ans.type="text";
                }
                return json

            }, //文本框
            multiple:function (){
                let json={
                    name: '多行文本框',
                    icon: 'mdi mdi-clipboard-text',
                    datas: {
                        name: {name: '控件名称', value: '多行文本框', type: 'text'},
                        placeholder: {name: '提示语句', value: '', type: 'text'},
                        // value: {name: '默认内容', value: '', type: 'textarea'},
                        height: {name: '控件高度', value: 80, type: 'number'},
                        required: {name: '是否必填', value: 0, options:[{"label":"选填","value":0},{"label":"必填","value":1}], type: 'radio'},
                        id: {name: '主键id', value: 0, type: 'hidden'},
                        uuid:{name: '控件标识', value:"", type: 'hidden'},
                        ans:{name: '正确答案', value: '', type: 'hidden'},
                    },
                    getHtml: function () {
                        return '<textarea name="' + this.datas.uuid.value + '" class="form-control form-val" cols="30" rows="5" style="resize: none;"></textarea>'
                    },
                };
                if(self.fType===formType.Paper){
                    json.datas.ans.type="text";
                }

               return json;

            }, //多行文本框
            date:function (){
                if(self.fType===formType.Paper){
                   return null;
                }
                return{
                        name: '日期选择框',
                            icon: 'mdi mdi-calendar-clock',
                        datas: {
                            name: {name: '控件名称', value: '时间框', type: 'text'},
                            // value: {name: '默认内容', value: '', type: 'date'},
                            required: {name: '是否必填', value: 0, options:[{"label":"选填1","value":0},{"label":"必填2","value":1}], type: 'radio'},
                            id: {name: '主键id', value: 0, type: 'hidden'},
                            uuid:{name: '控件标识', value:"", type: 'hidden'}
                        },
                        getHtml: function () {
                            return '<input name="' + this.datas.uuid.value + '"   type="date" class="form-control form-val date-input" value>'
                        },

                    }
            },
            radio: function (){
                let json={
                    name: '单选框',
                    icon: 'mdi mdi-radiobox-marked',
                    datas: {
                        name: {name: '控件名称', value: '单选框', type: 'text'},
                        // value: {name: '默认勾选', value: 0, type: 'text'},
                        options: {name: '单选框选项', value:[{"label":"选项1","value":self.getUUID("radio")},{"label":"选项1","value":self.getUUID("radio")}], type: 'opt-edit'},
                        ans:{name: '正确答案', value: '', type: 'hidden',placeholder:"选项序号"},
                        required: {name: '是否必填', value: 0, options:[{"label":"选填","value":0},{"label":"必填","value":1}], type: 'radio'},
                        rand:{name: '是否乱序',value:0, options:[{"label":"否","value":0},{"label":"是","value":1}], type: 'radio'},
                        id: {name: '主键id', value: 0, type: 'hidden'},
                        uuid:{name: '控件标识', value:"", type: 'hidden'},
                    },
                    getHtml: function () {
                    return self.getRadioByTextAreaValue(this.datas.options.value,  this.datas.uuid.value)
                },
            }
                if(self.fType===formType.Paper){
                    json.datas.ans.type="text";
                }
                return json;

            }, //单选框
            checkbox: function (){
                let json={

                    name: '多选框',
                    icon: 'mdi mdi-checkbox-marked-outline',
                    datas: {
                        name: {name: '控件名称', value: '多选框', type: 'text'},
                        // value: {name: '默认勾选', value: '多选一\n多选二', type: 'textarea'},
                        options: {name: '多选框选项', value:[{"label":"选项1","value":self.getUUID("checkbox")},{"label":"选项1","value":self.getUUID("checkbox")}], type: 'opt-edit'},
                        ans:{name: '正确答案', value: '', type: 'hidden',placeholder:"选项序号,多个用逗号分隔"},
                        required: {name: '是否必填', value: 0, options:[{"label":"选填","value":0},{"label":"必填","value":1}], type: 'radio'},
                        rand:{name: '是否乱序',value:0, options:[{"label":"否","value":0},{"label":"是","value":1}], type: 'radio'},
                        id: {name: '主键id', value: 0, type: 'hidden'},
                        uuid:{name: '控件标识', value:"", type: 'hidden'},

                    },
                    getHtml: function () {
                        return self.getCheckBoxByTextAreaValue(this.datas.options.value, this.datas.uuid.value)
                    },
                };
                if(self.fType===formType.Paper){
                    json.datas.ans.type="text";
                }
                return json;
            }, //多选框
            select: function (){
                let json={
                    id: 0,
                    name: '下拉选择框',
                    icon: 'mdi mdi-format-list-checks',
                    datas: {
                        name: {name: '控件名称', value: '下拉选择框', type: 'text'},
                        // value: {name: '默认选择', value: '请选择省份', type: 'text'},
                        options: {name: '下拉选框选项', value:[{"label":"选项1","value":self.getUUID("checkbox")},{"label":"选项1","value":self.getUUID("checkbox")}], type: 'opt-edit'},
                        ans:{name: '正确答案', value: '', type: 'hidden',placeholder:"选项序号"},
                        required: {name: '是否必填', value: 0, options:[{"label":"选填","value":0},{"label":"必填","value":1}], type: 'radio'},
                        id: {name: '主键id', value: 0, type: 'hidden'},
                        uuid:{name: '控件标识', value:"", type: 'hidden'},

                    },
                    getHtml: function () {
                        return self.getSelectByTextAreaValue(this.datas.options.value, this.datas.uuid.value)
                    },
                }
                if(self.fType===formType.Paper){
                    json.datas.ans.type="text";
                }
                return json;
            }
        };
        self.el = '';
        self.elObj = null;
        self.fType=1;   //1->问卷|2->试卷
        self.formConfig = {
            //  required: {name: '是否必填', value: 0, options:[{"label":"选填","value":0},{"label":"必填","value":1}], type: 'radio'},
            // width: { name: '组件标签宽度', value: '100', type: 'number' },
            align: {name: '标签对齐方式', value: 0, options: [{"label":"右侧对齐","value":0},{"label":"顶部对齐","value":1},{"label":"左侧对齐","value":2}], type: 'radio'},
            rand: {name: '是否乱序', value: 0, options:[{"label":"否","value":0},{"label":"是","value":1}], type: 'radio'},
        };
        self.doSubmit=function (data) {
            alert(JSON.stringify(data))
        };
        self.doCancel=function (data){
            alert(JSON.stringify(data))
        }
    };
    //REDO 重构
    formDesign.prototype = {

        build: function (params) {

            //先清除对应div中的html代码
            let self = this;
            if (params['el']) {
                self.el = params['el']
            }
            self.elObj = $(self.el);
            self.elObj.empty()
            self.type=params.type;

            if(params.type===designType.Preview){
                let f=$("<form class='form-subject-form'></form>");
                f.appendTo(self.el);
                self.buildForm(params.data,'.form-subject-form');
                f.css({"padding":"5px 5px 50px 5px"});
                if(self.isMobile()){
                    self.elObj.append("<div class='btn-group m-btn-form-group'><a class='btn btn-success' id='submit-form'>确定</a><a  id='cancel-form' class='btn btn-danger'>取消</a></div>")
                    //self.elObj.find('.m-btn-form-group')
                }else{
                    f.append("<div class='row btn-group btn-form-group'><a class='btn btn-success' id='submit-form'>确定</a><a  id='cancel-form' class='btn btn-danger'>取消</a></div>")
                }



                //初始化注册相关事件
                self.event();
                return
            }

            let height = '100%'
            if (params['height']) {
                height = params['height']
            }
            self.elObj.height(height)
            let main = '<div class="diy-form">'
            main += self.leftToolbar()

            main += self.centerMain()
            main += self.rightAttribute()
            main += '</div><div class="drag-control"></div>'
            main += '<div class="preview-main"></div>'

            //添加基本的界面布局
            self.elObj.append(main)

            //$('.interval').css('height', document.body.offsetHeight + 'px') //初始化高度，跟浏览器可视高度一致
            self.buildForm(params.data);

            //初始化注册相关事件
            self.event();


        },
        leftToolbar: function () {
            //<!--左侧工具栏-->
            let str = '<div class="form-control-panel">',
                self = this;
            str += '<p class="form-title">工具栏</p>'
            str += '<div class="form-controls">'
            for (let key in self.controlMap) {
                let control=self.controlMap[key]();
                if(!control){
                    continue;
                }
                str += '<div class="control-name" data-type="' + key + '">'
                str += '<div class="control-real-name"><i  class="iconfont ' + control.icon + '"></i>' + control.name + '</div>'
                str += '</div>'
            }
            str += '</div></div>'
            return str
        },
        centerMain: function () {
            //<!--中间内容区域-->
            let str = '<div class="form-designer">'
            //<!--主体部分-->
             str += '<div class="form-subject prew ldg-right">'
             str += '<div class="form-button">'
             str +='<button class="btn btn-danger btn-xs form-clear-all"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span>清空</button>'
             str +='<span class="pull-right btn-group">'
             str +='<button class="btn btn-info btn-xs form-import"><span class="glyphicon glyphicon-import" aria-hidden="true"></span>导入JSON</button>'
             str +='<button class="btn btn-warning btn-xs form-export"><span class="glyphicon glyphicon-export" aria-hidden="true"></span>导出JSON</button>'
             str +='<button class="btn btn-success btn-xs form-preview"><span class="glyphicon glyphicon-sunglasses" aria-hidden="true"></span>预览表单</button>'
             str +='<button class="btn btn-default btn-xs form-config-show"><span class="mdi mdi-settings" aria-hidden="true"></span>表单属性</button>'
             str +='<button class="btn btn-primary btn-xs form-config-save"><span class="mdi mdi-content-save" aria-hidden="true"></span>保存表单</button>'
             str += '</span></div><form class="form-subject-form">'
             str += '</form>'
             str += '</div></div>'
            return str
        },
        rightAttribute: function () {
            //<!--右侧属性框-->
            var str = '<div class="form-config">'
            str += '<p class="form-title">表单属性  <button class="btn btn-danger btn-xs close-attr"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭</button></p>'
            str += '<div class="form-configs"></div></div>'
            str += '<div class="form-properties">'
            str += '<p class="form-title">组件设置  <button class="btn btn-danger btn-xs close-attr"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭</button></p>'
            str += '<div class="form-attribute" data-type=""></div>'

            str += '</div>'
            return str
        },
        buildForm: function (data, showel,cacheControl=true) {

            let self = this;
            if (!data) {
                return
            }
            data.topics.forEach( function (c) {
                self.addControl(c.type, c, showel,cacheControl)
            })
            for (let key in data.config) {
                if (self.formConfig[key]) {
                    self.formConfig[key].value = data.config[key];
                }
            }
            self.applyConfig(showel)
        },
        applyConfig: function (showel = ".prew") {
            let self = this;
            for (let key in self.formConfig) {
                self.changeConfig(key, self.formConfig[key].value, showel)
            }

        },
        addControl: function (type, typeinfo = null, previewel = "",cacheControl=true) {

            let self = this, typec = self.controlMap[type]();
            //唯一键
            typec.datas['uuid'].value=self.getUUID(type);
            if (typeinfo != null) {
                for (let key in typec.datas) {
                    if (typeinfo[key]) {
                        typec.datas[key].value = typeinfo[key];
                    }
                }
            }
            let isdiyform = false
            if (previewel === "") {
                previewel = '.form-subject-form';
                isdiyform = true
            }

            typec['type'] = type

            let str = self.switchType(typec, type, isdiyform)

            //获取当前中部控件，删除放置效果及处理单选框多选框name相同的问题
            let item = $(previewel).find('.row')

            if (item.length > 0) {
                //判断是否位置放好了，有时候没有放置在控件上，就放置到最底层
                let isSelectPosition = false
                for (let i = 0; i < item.length; i++) {
                    if (item.eq(i).hasClass('place-location-bottom')) {
                        if (cacheControl) {
                            self.controlCache.splice(i + 1, 0, typec)
                        }
                        item.eq(i).after(str)
                        self.object = $(item.eq(i)).next()
                        item.eq(i).removeClass('place-location-bottom')
                        isSelectPosition = true
                    } else if (item.eq(i).hasClass('place-location-top')) {
                        if (cacheControl) {
                            self.controlCache.splice(i, 0, typec)
                        }
                        item.eq(i).before(str)
                        self.object = $(item.eq(i)).prev()
                        item.eq(i).removeClass('place-location-top')
                        isSelectPosition = true
                    }
                }
                if (!isSelectPosition) {
                    self.object = $(str).appendTo(previewel)
                    if (cacheControl) {
                        self.controlCache.push(typec)
                    }
                }
            } else {
                self.object = $(str).appendTo(previewel)
                if (cacheControl) {
                    self.controlCache.push(typec)
                }
            }

            self.object = $(self.object).find(".form-item")
            if (typeinfo != null&&cacheControl) {
                self.changeControl('id', typeinfo['uuid'], 'text')
                for (let key in typeinfo) {
                    self.changeControl(key, typeinfo[key], type, typec.datas)
                }
            }
        },
        changeConfig: function (key, value, showel) {
            if (key === "width") {
                $(showel + " .form-item-head").width(value)
            } else if (key === "align") {
                $(showel).removeClass("ldg-right").removeClass("ldg-left").removeClass("ldg-top")
                value=parseInt(value);
                if (value === 0) {
                    $(showel).addClass("ldg-right")
                } else if (value === 2) {
                    $(showel).addClass("ldg-left")
                }else{

                    $(showel).addClass("ldg-top")
                }
            }
        },
        switchType: function (typeinfo, type, isdiy) {

            let self = this;
            if ('undefined' !== typeof typeinfo.getDiyHtml) {
                return typeinfo.getDiyHtml(isdiy)
            }
            if ('undefined' !== typeof typeinfo.getHtml) {
                let html = '<div class="row"><div class="form-item" data-uuid="' + typeinfo.datas.uuid.value + '"   data-id="' + typeinfo.datas.id.value + '" data-type="' + type + '">' + '<div class="form-item-head"><div class="form-item-name">' + self.getRequired(typeinfo.datas.required.value) + '<span>' + typeinfo.datas.name.value + '</span>' + '</div></div>';
                if (isdiy) {
                    html += self.getBtns(typeinfo.btns, typeinfo.datas.uuid.value)
                }
                html += '<div class="form-item-content"><div class="form-group ">' + typeinfo.getHtml(isdiy) + '</div>' + self.getCheck(typeinfo.datas.required, typeinfo.datas.check) + '</div>'
                return html
            }
            return "";
        },
        getBtns: function (btns, id) {
            let self = this, str = '<!--表单控件的功能按钮-->'
            str += '<div class="form-item-group-button">'
           // str += '<span class="form-item-id">' + id + '</span>'
            if (btns) {
                for (let key in btns) {
                    str += '<i  class="iconfont ' + btns[key].class + '"></i>'
                }
            } else {
                for (let key in self.defaultBtns) {
                    str += '<i  class="iconfont ' + self.defaultBtns[key].class + '"></i>'
                }
            }
            str += '</div>'
            return str
        },
        changeControl: function (attrKey, attrValue, attrType, datas) {

            let self = this;
            if (attrKey === 'name') {
               self.object.find('.form-item-name span').text(attrValue)
            } else if (attrKey === 'options' || attrKey === 'value') {
                let tempid = self.object.data('uuid')
                let temphtml = '未知的类型'
                let upval = false
                if (attrType.indexOf('radio') === 0) {
                    temphtml = self.getRadioByTextAreaValue(datas.options.value,  tempid)
                } else if (attrType.indexOf('checkbox') === 0) {
                    temphtml = self.getCheckBoxByTextAreaValue(datas.options.value,  tempid)
                } else if (attrType.indexOf('select') === 0) {
                    temphtml = self.getSelectByTextAreaValue(datas.options.value, tempid)
                } else {
                    upval = true
                }
                if (upval) {
                    self.object.find('.form-val').val(attrValue)
                } else {
                    self.object.find('.form-group').html(temphtml)
                }

            } else if (attrKey === 'uuid') {
                self.object.find('.form-item-id').text(attrValue)
                self.object.data('uuid', attrValue)
            } else if (attrKey === 'placeholder') {
                self.object.find('.form-val').attr('placeholder', attrValue)
            } else if (attrKey === 'height') {
                self.object.find('.form-val').height(attrValue)
            } else if (attrKey==='required') {
                attrValue=parseInt(attrValue);
                if (attrValue===1) {
                    self.object.find('.required').removeClass("hidden");
                } else {
                    self.object.find('.required').addClass("hidden");
                }
            } else if (attrKey === 'check') {
                self.object.data("check", attrValue)
            }


        },
        getRadioByTextAreaValue: function (opts, id) {


            let self = this,
             str = ''
            opts.forEach(function (opt) {
                if (opt) {

                    str += '<div class="radio"><label><input type="radio" name="'+id+'" value="'+opt.value+'" >'+opt.label+'</label></div>'
                }
            })
            return str
        },
        getCheckBoxByTextAreaValue: function (opts, id) {

            let str = ''
            opts.forEach(function (opt) {
                if (opt) {
                    let checked = ''

                    str += '<div class="checkbox"><label><input type="checkbox" name="'+id+'" value="'+opt.value+'" >'+opt.label+'</label></div>'
                }
            })
            return str
        },
        getSelectByTextAreaValue: function (opts, id) {

            let self=this,
                str = '<select name='+id+' class="form-control">';

            opts.forEach(function (opt){
                str += "<option value="+opt.value+">"+opt.label+"</option>";
            })
            str += '</select>'
            return str;

        },
        refreshControlCache:function (){

            let self=this,arr=[];
            $('.form-subject-form .form-item').each(function (){

                let item=$(this),
                     uuid=item.attr('data-uuid');

                for(let i in self.controlCache){
                    let control=self.controlCache[i];
                    if(control.datas["uuid"].value===uuid){
                        arr.push(control);
                        break;
                    }
                }
            });
            self.controlCache=arr;
        },
        saveForm:function (data){
            alert(JSON.stringify(data))
        },
        event: function () {
            let self = this;

            if ($('#form-export').length === 0&&self.type===designType.Design) {

                //左侧工具栏鼠标按下控件事件
                self.elObj.on('mousedown', '.control-name', function (e) {
                    e.preventDefault()
                    mouseX = e.clientX //获取鼠标所在的x坐标
                    mouseY = e.clientY //获取鼠标所在的y坐标
                    self.controlHtml = $(this).prop('outerHTML')
                    let style = 'class="control-name control-name-move" '
                    style += 'style="width:' + $(this).width() + 'px;'
                    style += 'position: absolute;'
                    style += 'background: #fff;'
                    style += 'z-index: 100;'
                    style += 'top: ' + new Number(self.mouseY - $(this).height() / 2) + 'px;'
                    style += 'left: ' + new Number(self.mouseX - $(this).width() / 2) + 'px;'
                    style += '"'
                    self.controlHtml = self.controlHtml.replace('class="control-name"', style)
                    $('.drag-control').append(self.controlHtml)
                    //获取form的坐标
                    let subjectForm = $('.form-subject')
                    self.formLeft = subjectForm.offset().left
                    self.formTop = subjectForm.offset().top
                    self.formRight = self.formLeft + subjectForm.width()
                    self.formBottom = self.formTop + subjectForm.height()
                    //按下了控件,触发滑动事件里的效果
                    self.isDownControl = true
                    $('.diy-form').removeClass('has-properties')
                })

                //左侧工具栏鼠标松开控件事件
                self.elObj.on('mouseup', '.control-name', function (e) {
                    e.preventDefault()
                    //松开了控件，不触发滑动事件里的效果
                    self.isDownControl = false
                    let type = $(this).data('type')
                    //处于放置的位置才能在中部区域增加控件
                    if (self.isCanBePlaced) {
                        self.isCanBePlaced = false
                        self.addControl(type)
                        self.applyConfig()
                    }
                    $('.form-subject-form').removeClass('place-location-bottom')
                    $('.form-subject-form').removeClass('place-location-top')
                    $('.drag-control').empty()
                })


                //中部控件删除事件
                self.elObj.on('click', '.control-delete', function (e) {
                    e.stopPropagation() //阻止事件冒泡
                    let index = $(this).index('.control-delete')
                    $('.form-subject-form').children().eq(index).remove()
                    $('.diy-form').removeClass('has-properties')
                    self.controlCache.splice(index, 1)
                })
                self.elObj.on('click', '.control-up', function (e) {
                    e.stopPropagation() //阻止事件冒泡
                    let curRow=$(this).closest('.row'),
                        prevRow=curRow.prev();
                    if(prevRow){
                        prevRow.before(curRow)
                        self.refreshControlCache()
                    }


                })
                self.elObj.on('click', '.control-down', function (e) {
                    e.stopPropagation() //阻止事件冒泡
                    let curRow=$(this).closest('.row'),
                        nextRow=curRow.next();
                    if(nextRow){
                        nextRow.after(curRow)
                        self.refreshControlCache()
                    }
                })

                //中部控件按下事件
                self.elObj.on('mousedown', '.control-move', function (e) {
                    e.preventDefault()
                    self.mouseX = e.clientX //获取鼠标所在的x坐标
                    self.mouseY = e.clientY //获取鼠标所在的y坐标
                    self.controlHtml = $(this).parents('.row').html()
                    let style = 'class="form-item form-item-move" '
                    style += 'style="width:' + $(this).parents('.row').width() + 'px;'
                    style += 'position: absolute;'
                    style += 'background: #fff;'
                    style += 'z-index: 100;'
                    style += 'top: ' + new Number(self.mouseY - $(this).parents('.row').height()) + 'px;' // / 2是中间
                    style += 'left: ' + new Number(self.mouseX - $(this).parents('.row').width()) + 'px;'
                    style += '"'
                    self.controlHtml = self.controlHtml.replace('class="form-item"', style)
                    self.controlHtml = '<div class="row">' + self.controlHtml + '</div>'
                    $('.drag-control').append(self.controlHtml)
                    //获取form的坐标
                    let LdgFormSubjectForm = $('.form-subject')
                    self.formLeft = self.getRealLocationLeft(LdgFormSubjectForm, 0)
                    self.formTop = self.getRealLocationTop(LdgFormSubjectForm, 0)
                    self.formRight = self.formLeft + LdgFormSubjectForm.width()
                    self.formBottom = self.formTop + LdgFormSubjectForm.height()
                    //按下了控件,触发滑动事件里的效果
                    self.isDownControl = true

                    let index = $(this).index('.control-move')
                    $('.form-subject-form').children().eq(index).remove()
                })

                //中部控件松开事件
                self.elObj.on('mouseup', '.form-item-move', function (e) {

                    e.preventDefault()
                    $(this).removeAttr('style')
                    let str = $('.form-item-move').parents('.drag-control').html()
                    str = str.replace(' form-item-move', '')

                    //获取当前中部控件，删除放置效果
                    let item = $('.form-subject-form').find('.row')
                    //处于放置的位置才能在中部区域增加控件
                    if (self.isCanBePlaced && self.isDownControl) {
                        if (item.length > 0) {
                            //判断是否位置放好了，有时候没有放置在控件上，就放置到最底层
                            let isSelectPosition = false
                            for (let i = 0; i < item.length; i++) {
                                if (item.eq(i).hasClass('place-location-bottom')) {
                                    item.eq(i).after(str)
                                    item.eq(i).removeClass('place-location-bottom')
                                    isSelectPosition = true
                                } else if (item.eq(i).hasClass('place-location-top')) {
                                    item.eq(i).before(str)
                                    item.eq(i).removeClass('place-location-top')
                                    isSelectPosition = true
                                }
                            }
                            if (!isSelectPosition) {
                                $('.form-subject-form').append(str)
                            }
                        } else {
                            $('.form-subject-form').append(str)
                        }
                    } else {
                        //放置在其他地区时，直接删除样式，添加到最后一个位置
                        if (item.length > 0) {
                            //删除样式
                            for (var i = 0; i < item.length; i++) {
                                item.eq(i).removeClass('place-location-bottom')
                                item.eq(i).removeClass('place-location-top')
                            }
                        }
                        $('.form-subject-form').append(str)
                    }

                    $('.form-subject-form').removeClass('place-location-bottom').removeClass('place-location-top')

                    //松开了控件，不触发滑动事件里的效果
                    self.isDownControl = false
                    $('.drag-control').empty()
                    self.refreshControlCache();
                })

                //中间控件点击事件（显示右侧属性栏）
                self.elObj.on('click', '.prew .form-item', function () {
                    $('.diy-form').addClass('has-properties')
                    $(".form-properties").addClass("show-attr")
                    $(".form-config").removeClass("show-attr")
                    self.object = $(this)
                    self.objectIndex = $('.prew .form-item').index($(this))
                    let datas = self.controlCache[self.objectIndex].datas
                    self.attributeShow('.form-attribute', datas)
                })

                //修改控件属性 改变属性 修改属性 属性修改 组件设置
                self.elObj.on('change', '.form-attribute .form-group', function () {

                    let temptypekey = self.object.data('type') //当前控件的类型
                    let tempkey = $(this).attr('attrname') //修改的参数名称
                    let control=self.controlCache[self.objectIndex]
                    let temptype = control.datas[tempkey].type //要修改的参数类型
                    let tempvalue = self.getAttrValue($(this), temptype);
                    control.datas[tempkey].value = tempvalue;
                    self.changeControl(tempkey, tempvalue, temptypekey,control.datas)
                })

                //表单属性 属性修改
                self.elObj.on('change', '.form-configs .form-group', function () {

                    let tempkey = $(this).attr('attrname') //修改的参数名称
                    let temptype = self.formConfig[tempkey].type //要修改的参数类型
                    let tempvalue = self.getAttrValue($(this), temptype)
                    self.formConfig[tempkey].value = tempvalue
                    self.changeConfig(tempkey, tempvalue, ".prew")
                })
                //修改单选框、复选框、下拉框、文本下拉框的选项值
                self.elObj.on('change', '.select-attr', function () {
                    let val = $(this).val()
                    if (val !== '') {
                        var spilts = val.split('\n')
                        var inputName = 'selectName'
                        if (self.object.data('type') === 'radio' || self.object.data('type') === 'checkbox') {
                            var checkMargin = self.object.find('.check-margin')
                            if (checkMargin != null && checkMargin.length > 0) {
                                inputName = checkMargin.eq(0).attr('name')
                            }
                        }
                        self.object.find('.form-group').children().remove()
                        let str = ''
                        if (self.object.data('type') === 'select') {
                            str += '<select class="form-control">'
                        } else if (self.object.data('type') === 'textdropdown') {
                            str += '<input type="text" class="form-control"><div class="select-input-div" title="下拉菜单">'
                        }

                        for (let i = 0; i < spilts.length; i++) {
                            if (spilts[i] !== '') {
                                str += self.getMoreHtml(self.object.data('type'), spilts[i], inputName)
                            }
                        }

                        if (self.object.data('type') ==='select') {
                            str += '</select>'
                        }
                        self.object.find('.form-group').append(str)
                    }
                });
                //鼠标移动事件
                document.onmousemove = function (e) {

                    e.preventDefault()
                    if (self.isDownControl) {
                        self.mouseX = e.clientX //获取鼠标所在的x坐标
                        self.mouseY = e.clientY //获取鼠标所在的y坐标
                        //让鼠标在控件的中心位置
                        let width=$('.control-name-move').width() / 2,
                            height= $('.control-name-move').height() / 2;
                        $('.control-name-move').css({"top": self.mouseY - height + 'px',"left":self.mouseX - width + 'px'});
                        let widthItem = $('.form-item-move').width() - 30 // / 2是中间
                            ,heightItem = $('.form-item-move').height() - 30
                        $('.form-item-move').css({"top":self.mouseY - heightItem + 'px',"left":self.mouseX - widthItem + 'px'});

                        if (self.formLeft < self.mouseX && self.mouseX < self.formRight && self.formTop < self.mouseY && self.mouseY < self.formBottom) {
                            //是否可以放置
                            self.isCanBePlaced = true

                            //获取中部的控件
                            var item = $('.form-subject-form').find('.row')
                            if (item.length > 0) {
                                //先删除放置的位置样式
                                for (let i = 0; i < item.length; i++) {
                                    item.eq(i).removeClass('place-location-bottom').removeClass('place-location-top')
                                }
                                $('.form-subject-form').removeClass('place-location-bottom').removeClass('place-location-top')

                                //判断是否位置放好了，有时候没有放置在控件上，就放置到最底层
                                let isSelectPosition = false
                                for (let i = 0; i < item.length; i++) {
                                    let itemTop = self.getRealLocationTop(item.eq(i), 0)
                                        ,itemCenter = itemTop + item.eq(i).height() / 2
                                        ,itemBottom = itemTop + item.eq(i).height()
                                    //根据鼠标和控件的位置，判断是在哪个控件上
                                    if (itemTop < self.mouseY && self.mouseY < itemCenter) {
                                        //处于该控件上半部分
                                        item.eq(i).addClass('place-location-top')
                                        isSelectPosition = true
                                    } else if (itemCenter < self.mouseY && self.mouseY < itemBottom) {
                                        //处于该控件下半部分
                                        item.eq(i).addClass('place-location-bottom')
                                        isSelectPosition = true
                                    }
                                }
                                if (!isSelectPosition) {
                                    $('.form-subject-form').addClass('place-location-bottom')
                                }
                            } else {
                                $('.form-subject-form').addClass('place-location-top')
                            }
                        } else {
                            self.isCanBePlaced = false
                        }
                    }
                }

                $('body').append(
                    '<div class="modal fade" id="form-export" tabindex="-1" role="dialog"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title">导出JSON</h4></div><div class="modal-body"><textarea class="form-control" style="resize:none;height:600px"></textarea></div></div></div></div><div class="modal fade" id="form-import" tabindex="-1" role="dialog"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title">导入JSON</h4></div><div class="modal-body"><textarea class="form-control" style="resize:none;height:600px"></textarea></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">取消</button> <button type="button" class="btn btn-primary" data-dismiss="modal">确认导入</button></div></div></div></div><div class="modal fade" id="form-preview" tabindex="-1" role="dialog"><div class="modal-dialog " role="document"><div class="modal-content form-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title">表单预览</h4></div><div class="modal-body"><form></form></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">取消</button> <button type="button" class="btn btn-primary">提取数据</button></div></div></div></div><div class="modal fade" id="form-data" tabindex="-1" role="dialog"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title">表单数据</h4></div><div class="modal-body"><textarea class="form-control" style="resize:none;height:600px"></textarea></div></div></div></div>'
                )
                $('#form-import .btn-primary').click(function () {
                    //导入JSON数据到设计窗口
                    self.importJson($('#form-import textarea').val())
                })

                $('#form-preview .btn-primary').click(function () {

                    let showel = ".modal-body .form-subject-form"

                    //提取表单数据
                    if (self.checkForm(showel)) {
                        $("#form-preview").modal("hide");
                        let json = self.getForm(showel, true);
                        $("#form-data").modal("show")
                        $('#form-data textarea').val(json)
                    }


                })

                //====================右侧属性设计相关事件start===========================
                self.elObj.on("click",'.opt-operator>span',function (){

                    let obj=$(this),
                        optRow=obj.closest(".opt-row"),
                        formGroup=obj.closest(".form-group");
                    if(obj.hasClass('opt-up')){
                        let prev=optRow.prev();
                        if(prev){
                            prev.before(optRow)

                        }
                    }else if(obj.hasClass('opt-down')){
                        let next=optRow.next();
                        if(next){
                            next.after(optRow)
                        }
                    }else if(obj.hasClass('opt-del')){
                        optRow.remove();

                    }else if(obj.hasClass('opt-add')){

                        let dataValue=self.getUUID("opt")
                            ,html='<div class="form-inline opt-row"><input type="text" class="form-control  input-sm" data-value='+dataValue+' value="选项"><div class="btn-group opt-operator"><span class="text opt-up text-info mdi mdi-arrow-up-bold-circle-outline"></span><span class="text opt-down text-warning mdi mdi-arrow-down-bold-circle-outline"></span><span class="text opt-add text-success mdi mdi-plus-circle"></span><span class="text opt-del text-danger mdi mdi-delete-circle"></span></div></div>'
                        optRow.after($(html));

                    }

                    formGroup.change();


                })
                //关闭属性
                self.elObj.on('click', '.close-attr', function () {
                    $('.diy-form').removeClass('has-properties')
                })
                //表单属性
                self.elObj.on('click', '.form-config-show', function () {
                    $('.diy-form').addClass('has-properties')
                    $(".form-config").addClass("show-attr")
                    $(".form-properties").removeClass("show-attr")
                    self.attributeShow('.form-configs', self.formConfig)
                })
                //====================右侧属性设计相关事件end===========================

                //=============================按钮操作start=======================
                //清空
                self.elObj.on('click', '.form-clear-all', function () {
                    self.clear()
                })

                //导入
                self.elObj.on('click', '.form-import', function () {
                    $('#form-import').modal('show')
                })

                //导出
                self.elObj.on('click', '.form-export', function () {
                    let json = self.exportJson(true)
                    $('#form-export .modal-body textarea').val(json)
                    $('#form-export').modal('show')
                })

                //预览
                self.elObj.on('click', '.form-preview', function () {
                    $("#form-preview").modal("show");
                    let showel = "#form-preview .modal-body form"
                    $(showel).empty()
                    if (!$(showel).hasClass("form-subject-form")) {
                        $(showel).addClass("form-subject-form");
                    }
                    let json = self.exportJson()
                    self.importJson(json, showel,false);
                })
                //保存配置
                self.elObj.on('click','.form-config-save',function (){

                    //获取表单数据
                    let data=self.getFormData();
                    self.saveForm(data);

                });
                //=============================按钮操作end=======================

            }

            //提交表单
            self.elObj.on('click','#submit-form',function (){
                if(!self.checkForm(self.el)){
                    return
                }
                let json = self.getForm('.form-subject-form', true,false);
                self.doSubmit(json);
            });
            //取消
            self.elObj.on('click','#cancel-form',function (){
                let json = self.getForm('.form-subject-form', true,false);
                self.doCancel(json);
            });
            //验证事件
            //文本框的修改事件，验证正则表达式
            self.elObj.on("change", ".form-val", function () {

                //控件的顶层父类
                let obj = $(this).closest(".form-item");
                let index = $('.form-subject-form .form-item').index(obj);
                let control = self.controlCache[index];
                self.textRegExp(obj, control);

            });


        },
        //获取控件在整个页面中的真实位置X
        getRealLocationLeft: function (val, left) {
            let self = this;
            if (val[0].nodeName !== '#document') {
                left += val.position().left
                left = self.getRealLocationLeft(val.parent(), left)
            }
            return left
        },
        //获取控件在整个页面中的真实位置Y
        getRealLocationTop: function (val, top) {
            let self = this;
            if (val[0].nodeName !== '#document') {
                top += val.position().top
                top = self.getRealLocationTop(val.parent(), top)
            }
            return top
        },
        //获取单选框、复选框、下拉框、文本下拉框的html
        getMoreHtml: function (type, inputval, inputName) {
            let self = this, str = ''
            if (type === 'radio') {
                str += '<div class="form-check"><label class="form-check-label"><input type="radio" class="form-check-input check-margin" name="' + inputName + '" value="' + inputval + '">' + inputval + '</label></div>'
            } else if (type === 'checkbox') {
                str += '<div class="form-check"><label class="form-check-label"><input type="checkbox" class="form-check-input check-margin" name="' + inputName + '" value="' + inputval + '">' + inputval + '</label></div>'
            } else if (type === 'select') {
                str += '<option>' + inputval + '</option>'
            } else if (type === 'textdropdown') {
                str += '<p>' + inputval + '</p>'
            }
            return str
        },
        attributeShow: function (showel, datas) {
            let attribute = $(showel)
            if (datas) {
                //$('.form-attribute').html(controlList[object.data('type')].attr)
                let html = ''
                for (let key in datas) {

                    let data=datas[key],cvalue = data.value;
                    if (datas[key].type === 'text' || datas[key].type ==='number' || datas[key].type === 'date') {
                        let placehoder=data.placeholder
                        if(!placehoder){
                            placehoder=''
                        }
                        //字符串输入框属性
                        html += '<div class="form-group" attrname="'+key+'"><label>'+datas[key].name+'</label><input type="'+datas[key].type+'" value="'+cvalue+'" class="form-control" placeholder="'+placehoder+'"></div>'
                    } else if (datas[key].type ==='textarea') {
                        //多行字符串输入框属性
                        html += '<div class="form-group" attrname="'+key+'"><label>'+datas[key].name+'</label> <textarea class="form-control" rows="5">'+cvalue+'</textarea></div>'
                    } else if (datas[key].type ==='select') {
                        //下拉框属性
                        html += '<div class="form-group"  attrname="'+key+'"><label>'+datas[key].name+'</label><select class="form-control">'
                        let tempselected = ''
                        for (let i in datas[key].options) {
                            let curOpt=datas[key].options[i]
                            if (curOpt.key===cvalue) {
                                tempselected = 'selected'
                            }
                            html += '<option '+tempselected+' value='+curOpt.key+'>'+curOpt.value.name+'</option>'
                        }
                        html += '</select>'
                       // html += '<input type="text" class="form-control custom" placeholder="自定义正则" style="display: ' + (cvalue==="custom" ? 'inline-block' : 'none') + ';" value="' + customVal + '"></input>'
                        html += '</div>'
                    } else if (datas[key].type ==='radio') {

                        //单选框属性
                        html += '<div class="form-group"  attrname="'+key+'"><label>'+datas[key].name+'</label><div class="row">'
                        let radioclass = "col-lg-6";
                        if (Object.keys(datas[key].options).length != 2) {
                            radioclass = "col-lg-12";
                        }
                        for (let key2 in datas[key].options) {
                            let opt=datas[key].options[key2]

                            let tempchecked = ''
                            if (opt.value.toString()=== cvalue.toString()) {
                                tempchecked = 'checked'
                            }
                            html += '<div class="'+radioclass+'"><div class="form-check"><label class="form-check-label"><input type="radio" class="form-check-input" '+tempchecked+' name="'+key+'" value="'+opt.value+'">'+opt.label+'</label></div></div>';
                        }
                        html += '</div></div>'
                    }else if(datas[key].type==='opt-edit'){

                        //单选框属性
                        html += '<div class="form-group"  attrname="'+key+'"><label>'+datas[key].name+'</label>'


                        for (let key2 in datas[key].value) {
                            let opt=datas[key].value[key2]
                            let tempchecked = ''
                            if (opt.label=== cvalue) {
                                tempchecked = 'checked'
                            }
                            html += '<div class="form-inline opt-row"><input type="text" class="form-control col-lg-8 input-sm" data-value='+opt.value+' value='+opt.label+'><div class="btn-group opt-operator"><span class="text opt-up text-info mdi mdi-arrow-up-bold-circle-outline"></span><span class="text opt-down text-warning mdi mdi-arrow-down-bold-circle-outline"></span><span class="text opt-add text-success mdi mdi-plus-circle"></span><span class="text opt-del text-danger mdi mdi-delete-circle"></span></div></div>'
                        }
                        html += '</div>'
                    }
                }
                $(showel).html(html)
            } else {
                $(showel).html('无属性选项')
                return;
            }

        },
        getRequired: function (required) {

            if (required) {
                return '<div class="required">*</div>'
            }
            return '<div class="required hidden">*</div>'
        },
        getCheck: function (required, check = false) {
            if (required || check) {
                return '<div class="error-info"></div>'
            }
            return '<div class="error-info block-hide"></div>'
        },
        getCustomValue:function (obj,tempvalue){
            if (tempvalue ==='custom') {
               let val=$(obj).find('.custom').val()
                //如果有其它选项,则支持输入自定义内容
                $(obj).find('.custom').show()
                return val;
            }
            $(obj).find('.custom').hide();
            return "";
        },
        getAttrValue: function (obj, type) {
            let self=this,tempvalue = null;
            if (type ==='text' || type ==='number' || type ==='date') {
                tempvalue = $(obj).find('input').val()
            } else if (type ==='textarea') {
                tempvalue = $(obj).find('textarea').val()
            } else if (type ==='select') {
                tempvalue = $(obj).find('option:selected').val()
            } else if (type==='radio') {
                tempvalue = $(obj).find('input:radio:checked').val()
            }else if(type==='opt-edit'){
                tempvalue=[];
                obj.find('input').each(function (i){
                    let o=$(this),
                        label=o.val(),
                        value=o.attr('data-value');

                    if(!value||value.length<=0){
                        value=self.getUUID("opt")
                    }
                    //{"label":"选项1","value":0}
                    tempvalue.push({"label":label,"value":value});
                });



            }
            return tempvalue
        },
        clear: function () {
            let self=this;
            $('.form-subject-form').empty()
            self.controlCache=[];

        },
        importJson: function (json, showel = "",cacheControl=true) {

            let self = this;
            try {
                let cd = JSON.parse(json)
                //if(showel==""){Clear()}
                self.buildForm(cd, showel,cacheControl);

            } catch (err) {
                alert('导入错误,请检查导入数据是否正确')
                console.log(err)
            }
        },
        getFormData:function (){

            let self = this, json = new Object()
            json.config = Object()
            for (let dname in self.formConfig) {
                json.config[dname] = self.formConfig[dname].value
            }

            json.topics = []
            self.controlCache.forEach((c, index) => {
                let newc = new Object()
                newc.type = c.type

                for (let dname in c.datas) {
                    newc[dname] = c.datas[dname].value;
                    // if(dname==="check"){
                    //     newc["customVal"] = c.datas[dname].customVal;
                    // }
                }
                json.topics.push(newc)
            })

            return json;

        },
        exportJson: function (preview = false) {
            let self = this,json=null;

            json=self.getFormData();
            if (preview) {
                return JSON.stringify(json, null, '\t')
            }
            return JSON.stringify(json)
        },
        getForm: function (showel, preview = false,toStr=true) {

            //所有值
            let formdata = $(showel).serializeArray();
            let json = [];
            $(showel).find('.form-item').each(function () {
                let item = $(this),
                    id = parseInt(item.attr('data-id')),
                    uuid = item.attr('data-uuid'), value =[];

                for (let i in formdata) {
                    if (formdata[i].name === uuid) {
                        value.push(formdata[i].value)
                    }
                }

                json.push({
                    "id": id,
                    "uuid": uuid,
                    "value": value.join(","),
                });

            });
            if(!toStr){
                return json;
            }


            if (preview) {
                return JSON.stringify(json, null, '\t')
            }
            return JSON.stringify(json)
        },
        //文本框正则表达式
        textRegExp: function (object, control) {

            let self=this;
            if (!control.datas.check) {
                return true;
            }

            let limit = control.datas.check.value;

            if (limit!=="noCheck"&&limit !==null && limit !=="") {


                limit=self.regexMap[limit];
                if(!limit.exp){
                    return true;
                }


                let val = object.find(".form-val").val(),
                    ok = new RegExp(limit.exp).test(val);
                if (val === "") {
                    object.find(".error-info").hide();
                    return true;
                }

                if (!ok) {
                    let errMsg = limit.msg;
                    if (!errMsg) {
                        if(!errMsg){
                            errMsg =self.formatNotify;
                        }
                    }
                    object.find(".error-info").text(errMsg).show();
                    return false;

                }


                return true;

            }
            return true
        },
        //选项是否必填
        isChoice: function (object, control) {
            let self = this, choice = $(object).find(".required").is(':visible')
            if (choice) {
                let type = control["type"];
                if (type === "text" || type === "multiple" || type === "date") {
                    let val = object.find(".form-val").val();//获取值，可用于文本框、多行文本框、时间框
                    let bool = self.textMultipleDateValIsNull(val);//判断string是否为空，不为空为真
                    self.showChoiceErrorInfo(object, bool);//显示必填的错误信息
                    return bool;
                } else if (type === "radio" || type === "checkbox") {
                    let val = self.getRadioCheckboxVal(object);//获取单选按钮、多选按钮的值
                    let bool = self.textMultipleDateValIsNull(val);//判断string是否为空，不为空为真
                    self.showChoiceErrorInfo(object, bool);//显示必填的错误信息
                    return bool;
                } else if (type === "select") {
                    //下拉框有默认值
                    return true;
                } else if (type === "textdropdown") {
                    let val = self.getTextdropdownVal(object);//获取单选按钮、多选按钮的值
                    let bool = self.textMultipleDateValIsNull(val);//判断string是否为空，不为空为真
                    self.showChoiceErrorInfo(object, bool);//显示必填的错误信息
                    return bool;
                } else if (type === "img" || type === "file") {
                    let bool = self.isImgFileValNull(object);
                    self.showChoiceErrorInfo(object, bool);//显示必填的错误信息
                    return bool;
                }
            }
            return true;
        },
        //校验表单
        checkForm: function (showel) {

            let self = this, checkForm = true;
            var Items = $(showel).find(".form-item");
           // let index = $(formGroup).index(Items);

            for (let i = 0; i < Items.length; i++) {
                let control = self.controlCache[i];
                var item = Items.eq(i);
                let bool = self.isChoice(item, control);//判断该控件是否需要填写

                if (!bool) {
                    checkForm = false
                }
                if (item.data("type") === "text") {
                    if (bool) {
                        if (!self.textRegExp(item, control)) {
                            checkForm = false
                        }

                    } else {
                        checkForm = false
                    }
                }
            }
            return checkForm
        },
        //显示必填的错误信息
        showChoiceErrorInfo: function (object, bool) {
            let  self=this;
            if (bool) {
                object.find(".error-info").hide();
            } else {
                object.find(".error-info").text(self.requiredNotify).show();
            }
        },
        //判断文本框、多行文本框、时间框的值是否为空，可用于判断字符串的值
        textMultipleDateValIsNull: function (val) {

            if (val !== null && val !== "") {
                return true;
            }
            return false;
        },
        //获取单选按钮、多选按钮的值
        getRadioCheckboxVal: function (object) {
            let val =[];

            let inputs = object.find("input");
            for (let i = 0; i < inputs.length; i++) {
                let checked = inputs.eq(i).prop("checked");
                if (checked) {
                    val.push(inputs.eq(i).val())
                    //val += inputs.eq(i).val() + "\n";
                }
            }
            if(val.length<=0){
                val=null;
            }
            // if (val.indexOf("\n") > -1) {
            //     val = val.substring(0, val.length - 2);
            // }
            return val;
        },
        //获取下拉框选中的值
        getDropdownVal: function (object) {
            let select = object.find("select");
            let val = select.val();
            return val;
        },
        //判断文本下拉框的值是否正确
        isTextdropdownValTrue: function (object, val) {
            let bool = false;
            let ps = object.find(".select-input-div").find("p");
            for (let i = 0; i < ps.length; i++) {
                let pval = ps.eq(i).text();
                if (val === pval) {
                    bool = true;
                    break;
                }
            }
            return bool;
        },
        //显示文本下拉框的下拉值
        showTextdropdown: function (object) {
            let ps = object.find(".select-input-div").find("p");
            let val = object.find(".selectInput").val();
            for (let i = 0; i < ps.length; i++) {
                let pval = ps.eq(i).text();
                if (pval.indexOf(val) > -1) {
                    ps.eq(i).show();
                    continue;
                }
                ps.eq(i).hide();
            }
            object.find(".select-input-div").show();
        },

    }

    $.formDesign={
        //构建
        build:function (param){

            let obj=new formDesign();
            //保存回调
            if(param.saveForm){
                obj.saveForm=param.saveForm
            }
            if(param.data.type){
                obj.fType=param.data.type;
            }
            if(param.doSubmit){
                obj.doSubmit=param.doSubmit;
            }
            if(param.doCancel){
                obj.doCancel=param.doCancel;
            }

            if(param.getUUID){
                //重写唯一串生成函数
                obj.getUUID=param.getUUID;
            }

            obj.build(param);

        }
    }


})(jQuery);
